<?php

namespace Common\Logic;
class CommonLogic
{
    /**
     *
     * @param $data
     * @return mixed
     */
    public function crop_format($data)
    {
        $base64 = json_decode($data, true);
        $crop = $base64 ?: $data;
        $base = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
        if (is_array($crop)) {
            foreach ($crop as &$item) {
                if (!realpath($item)) continue;
                $item = $base . $this->toAbs($item);
            }
            return $crop;
        }
        $p = realpath($data);
        if (!$p) return $data;
        return $base . $this->toAbs($data);
    }

    public function append_domain($path, $dir = '')
    {
        if (!$dir) $dir = C('CUSTOM_UPLOAD_CONFIG.rootPath');
        $realpath = $this->toAbs($dir);
        $co = $this->get_proto_domain() . $realpath;
        $res = rtrim($co, '/') . '/' . ltrim($path, '/');
        return $res;
    }

    public function get_proto_domain()
    {
        return (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
    }

    public function toAbs($path)
    {
        $realpath = realpath($path);
        if (!$realpath) return $path;
        $root = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT']);
        $relative = str_replace(DIRECTORY_SEPARATOR, '/', str_replace($root, '', $realpath));
        $relative = '/'.ltrim($relative, '/');
        return $relative;
    }

    public function de_json($data, $call = false)
    {
        $de = json_decode($data, true);
        if ($de) {
            foreach ($de as &$row) {
                if (is_callable($call) || function_exists($call)) {
                    $row = $call($row);
                }
            }
        }
        return $de;
    }

    /**
     * 对比以删除
     * @param $new
     * @param $old
     * @return bool
     */
    public function compare2del($new, $old)
    {
        if($new==null) {
            $new = [$new];
        }else if (!is_array($new) && !is_file($new)) {
            $new = json_decode($new);
        } else if (!is_array($new) && is_file($new)) {
            $new = [$new];
        }
        if (!is_array($old) && !is_file($old)) {
            $old = json_decode($old);
        } else if (!is_array($old) && is_file($old)) {
            $old = [$old];
        }
        if ((!is_array($old) && !$old) || (!is_array($new) && !$new)) return false;
        foreach ($old as $item) {
            if (!in_array($item, $new) && is_file($item)) {
                @unlink($item);
            }
        }
    }
}